<template>
  <div class="container">
    <div class="title" :style="titleStyle">
      <span>{{'▎ ' +  showTitle }}</span>
      <span class="iconfont title-icon" @click="showChoice = !showChoice" :style="titleStyle">&#xe6eb;</span>
      <div class="select-con" v-show="showChoice" :style="marginStyle">
        <div class="select-item" v-for="item in selectTypes" :key="item.key" @click="handleClick(item.key)">{{item.text}}</div>
      </div>
    </div>
    <div class="chart" ref="chartRef"></div>
  </div>
</template>

<script setup>
import { getThemeValue } from '@/utils/theme'

import { onMounted, onUnmounted, reactive, ref, computed, getCurrentInstance, useContext, watch, nextTick } from 'vue'
// import * as echarts from 'echarts'
// import request from '@/request'
import { useStore } from 'vuex'
// vue3 的 setup 中，我们现在只能使用 useStore 获得 store 的实例，然后使用 computed 来获得某一个状态，没有内置的类似 mapState 这样的函数

const store = useStore()
const theme = computed(() => store.state.theme)
watch(theme, () => {
  console.log('trend-theme-change')
  chartInstance.dispose()
  initChart()
  screenAdapter()
  updateChart()
})

const chartRef = ref(null)
let chartInstance = null

const ctx = useContext()
ctx.expose({ screenAdapter, chartRef })
const { proxy } = getCurrentInstance()
const state = reactive({
  data: null,
  choiceType: 'map',
  titleFontSize: 0
})
const showChoice = ref(false)
onMounted(() => {
  // 在组件创建完成之后 进行回调函数的注册
  nextTick()
  proxy.$socket.registerCallBack('trendData', getData)

  console.log('mounted')
  console.log('mounted-ref', chartRef)
  initChart()
  // getData()
  // 发送数据给服务器， 告诉服务器需要的数据
  proxy.$socket.send({
    action: 'getData',
    socketType: 'trendData',
    chartName: 'trend',
    value: ''
  })
  window.addEventListener('resize', screenAdapter)
  screenAdapter()
})
onUnmounted(() => {
  window.removeEventListener('resize', screenAdapter)
  proxy.$socket.unRegisterCallBack('trendData')
})

// const data = reactive()
function initChart () {
  console.log('initchart')
  const initOption = {
    grid: {
      left: '3%',
      top: '35%',
      right: '4%',
      bottom: '1%',
      containLabel: true
    },
    legend: {
      left: 20,
      top: '15%',
      icon: 'circle'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false // 是否具备间隙
    },
    yAxis: {
      type: 'value'
    }
  }
  console.log('trend', chartRef)
  chartInstance = proxy.$echarts.init(chartRef.value, theme.value)
  chartInstance.setOption(initOption)

}
// ret 就是服务端发送给客户端的图表的数据
function getData (res) {
  console.log('获取数据', chartRef)
  // const { data: res } = await request.get('trend')
  state.data = res
  console.log(selectTypes)

  updateChart()
}
function updateChart () {
  console.log('更新数据')
  const timeArr = state.data.common.month
  const valueArr = state.data[state.choiceType].data

  // 半透明的颜色值
  const colorArr1 = [
    'rgba(11, 168, 44, 0.5)',
    'rgba(44, 110, 255, 0.5)',
    'rgba(22, 242, 217, 0.5)',
    'rgba(254, 33, 30, 0.5)',
    'rgba(250, 105, 0, 0.5)'
  ]
  // 全透明的颜色值
  const colorArr2 = [
    'rgba(11, 168, 44, 0)',
    'rgba(44, 110, 255, 0)',
    'rgba(22, 242, 217, 0)',
    'rgba(254, 33, 30, 0)',
    'rgba(250, 105, 0, 0)'
  ]
  const seriesArr = valueArr.map((item, index) => {
    return {
      name: item.name,
      type: 'line',
      data: item.data,
      // 堆叠图片效果，stack的属性的值要相同
      stack: state.choiceType,
      areaStyle: {
        color: new proxy.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: colorArr1[index]
          }, // %0的颜色值
          {
            offset: 1,
            color: colorArr2[index]
          } // 100%的颜色值
        ])
      }
    }
  })
  const legentArr = valueArr.map(item => item.name)
  const dataOption = {
    xAxis: {
      data: timeArr
    },
    legend: {
      data: legentArr
    },
    series: seriesArr
  }
  chartInstance.setOption(dataOption)
}
function screenAdapter () {
  console.log('获取数据', chartRef)
  state.titleFontSize = chartRef.value.offsetWidth / 100 * 3.6
  // console.log(state.titleFontSize)
  const adapterOption = {
    legend: {
      itemWidth: state.titleFontSize,
      itemHeight: state.titleFontSize,
      itemGap: state.titleFontSize,
      textStyle: {
        fontSize: state.titleFontSize / 2
      }
    }
  }
  chartInstance.setOption(adapterOption)
  chartInstance.resize()
}
const selectTypes = computed(() => {
  console.log(state.data)
  if (!state.data) {
    return []
  } else {
    return state.data.type.filter(item => item.key !== state.choiceType)
  }
})
function handleClick (type) {
  state.choiceType = type
  updateChart()
  showChoice.value = false
}

const showTitle = computed(() => {
  if (!state.data) {
    return ''
  } else {
    return state.data[state.choiceType].title
  }
})

// 设置给标题的样式
const titleStyle = computed(() => {
  return {
    fontSize: state.titleFontSize + 'px',
    color: getThemeValue(theme.value).titleColor
  }
})
const marginStyle = computed(() => {
  return {
    marginLeft: state.titleFontSize + 'px'
  }
})
</script>
<style lang="less" scoped>
.title {
  position: absolute;
  left: 20px;
  top: 20px;
  z-index: 10;
  color: white;
  .title-icon {
    margin-left: 10px;
    cursor: pointer;
  }
  .select-con {
    background-color: #222733;
  }
}
</style>
